// 包含多个actionCreator的模块
// 同步action: 对象{type:'xxx',data:data}
// 异步action: 函数()

import { SET_HEAD_TITLE, RECEIVE_USER, SHOW_ERROR_MSG } from "./action-type";
import { reqLogin } from "../api";
import storage from "../utils/storageUtils";

export const setHeadTitle = (headTitle: string) => ({
  type: SET_HEAD_TITLE,
  data: headTitle,
});

// 接收用户的同步action
export const receiveUser = (user: any) => ({
  type: RECEIVE_USER,
  user,
});

// 登录失时显示错误信息的同步action
export const showErrorMsg = (errorMsg: any) => ({
  type: SHOW_ERROR_MSG,
  errorMsg,
});

// 实现异步登录的action
export const login = (username: any, password: any) => {
  return async (dispatch: any) => {
    // 执行ajax异步请求
    const res = await reqLogin(username, password);
    const result = res.data;
    // 如果成功 分发成功的action
    if (result.status === 0) {
      console.log("登录成功");
      const user = result.data;
      // 保存到local中
      storage.saveUser(user);
      // 分发用户的同步action
      dispatch(receiveUser(user));

      return 1;
    }
    // 如果失败 分发一个失败的action
    else {
      const msg = result.msg;
      dispatch(showErrorMsg(msg));
      return 0;
    }
  };
};
